package com.caldremch.androidfoundation.http.interceptor;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


/**
 *
 * @author Caldremch
 * @date 2018/11/6
 * @Email caldremch@163.com
 * @describe 请求头拦截
 *
 **/
public class HeadersInterceptor implements Interceptor {

    private Map<String, String> mHeaders;

    public HeadersInterceptor(Map<String, String> headers) {
        this.mHeaders = headers;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request.Builder builder = chain.request().newBuilder();
        if (mHeaders != null  && mHeaders.size() > 0) {
            Set<String> keys = mHeaders.keySet();

            try {
                for (String headerKey : keys) {
                    String value  = mHeaders.get(headerKey);
                    if (value != null) {
                        builder.addHeader(headerKey, value);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return chain.proceed(builder.build());
    }
}
